﻿@model IEnumerable<ApprovePath>

@{
    int appPrcId = Convert.ToInt32(ViewBag.AppPrcId);
    int minStep = 0;
    int maxStep = 0;
    int? empIdTest = ViewBag.EmpIdTest;
    string warningMsg = "";
    string tab = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
    string tabCur = tab;
    Layout = "~/Views/Shared/_LayoutEmpty.cshtml";
    
    GERPContext context = new GERPContext(true);
    ApproveProcess appProc = context.ApproveProcesses.First(o => o.AppPrcId == appPrcId);
    List<ApprovePath> appPaths = context.ApprovePaths.Include(o => o.Position).Where(o => o.AppPrcId == appPrcId && o.RecordStatus != "D").OrderBy(o=>o.StepNo).ToList();
    List<Employee> employees = context.Employees.Include(o=>o.Position.ExecutivePosition).Include(o=>o.MasNamePrefix).Where(o => o.RecordStatus != "D")
        .ToList().OrderBy(o=>(o.Position.PosNo??0).ToString().PadLeft(4, '0')).ToList();
    List<KeyValuePair<int, string>> listExecPos = new List<KeyValuePair<int, string>>();
    { 
        foreach(var exec1 in context.ExecutivePositions.Where(o=>o.RecordStatus == "U"))
        {
            var allEmployeeInExecPosId = from e in employees
                                         where e.Position.ExecPosId == exec1.ExecPosId
                                         select e == null ? "" : (e.Position != null ? "[" + e.Position.PosNo + " - " + e.Position.Name + "] " : "") +
                                                                 (e.MasNamePrefix != null ? e.MasNamePrefix.Name : "") +
                                                                 e.FirstName + " " + e.LastName + " " +
                                                                 (e.Position != null && e.Position.ExecutivePosition != null ? "  -  " +  e.Position.ExecutivePosition.Name : "");

            var result1 = allEmployeeInExecPosId.ToArray();
            string result = string.Join("\r\n", result1);
            listExecPos.Add(new KeyValuePair<int, string>(exec1.ExecPosId, result));
        }
    }
    Dictionary<int, string> execPosDic = new Dictionary<int, string>();
    ExecutivePosition exec = context.ExecutivePositions.First(o => o.ExecPosId == 251);
    List<Position> positionHeads = context.Positions.Where(o => o.ExecPosId == 251).ToList();
    List<int> positionHeadsId = (from ph in positionHeads where ph.RecordStatus != "D" select ph.PosId).ToList();
    List<Employee> employeeHeads = (from e in employees where e.PosId != null && positionHeadsId.Contains(e.PosId.Value) select e).ToList();
    List<string> empHeadName = (from e in employeeHeads.Where(o => o.RecordStatus != "D").ToList() select "[" + e.Position.PosNo + " - " + e.Position.Name + "]   " + e.FullName + "  -  " + e.Position.ExecutivePosition.Name).ToList();
    Employee testEmp = context.Employees.FirstOrDefault(o => o.EmpId == empIdTest);
    /*foreach(var epg in context.ExecPosGroups)
    {
        List<ExecPosGroupDtls> dtls = context.ExecPosGroupDtlses.Where(o => o.ExecPosGroupId == epg.ExecPosGroupId).ToList();
        List<Employee> empOfGroup = (from dtl2 in dtls join em in employees on dtl2.ExecPosId equals em.ExecPosId select em).ToList();
        string text = epg.ExecPosGroupName + " " + (empOfGroup.Any() ? " [" + empOfGroup.Count() + " เจ้าหน้าที่ คือ " + 
                        string.Join(", ", (from em in empOfGroup select em.FullName).ToArray()) + "]" 
                        : "[ไม่มีเจ้าหน้าที่]");
        execPosDic.Add(epg.ExecPosGroupId, text);
    }*/
    // Find warning
    try{minStep = appPaths.Min(o => o.StepNo);} catch{}
    try{maxStep = appPaths.Max(o => o.StepNo);} catch{}
    for(int i = minStep; i <= maxStep ; i++)
    {
        if(i == 0)
        {
            warningMsg = "ไม่มีขั้นตอนที่ 1";
        } else if(appPaths.All(o => o.StepNo != i))
        {
            warningMsg += "ไม่มีขั้นตอนที่" + i + "<br/>";
        }
    }
    string checkTrue = "<img width='15px' height='15px' src='" + Url.Content("~/Images/Icons/Check.png") + "' />";
    string checkFalse = "";//"<img width='15px' height='15px' src='" + Url.Content("~/Images/Icons/Cancel.png") + "' />";
    string aboutAs = "<img width='15px' height='15px' src='" + Url.Content("~/Images/Icons/about_us.png") + "' title='{0}' />";
}

<h4 class="header">ขั้นตอนการอนุมัติภายใต้ประเภท(@appProc.Name) ของระบบ @appProc.ApproveProcessGroup 
    &nbsp;&nbsp;&nbsp;&nbsp; @Html.ActionLink("เพิ่ม", "Create", new {appPrcId})</h4> 
<h4 class="DetailHeader">การตั้งค่าขั้นตอนการอนุมัติ</h4>
<div class="detail">
    @if(!string.IsNullOrWhiteSpace(warningMsg))
    {
        <div style="color: red; background: yellow">@Html.Raw(warningMsg)</div>
    }
    <table class="mystyle" style="text-align: center"> 
        <thead>
            <tr>
                <th rowspan="2">ขั้นตอนที่</th>
                <th rowspan="2">วิธีอ้างถึงผู้อนุมัติ</th>
                <th rowspan="2">อนุมัติโดย</th>
                @*<th colspan="4">สิทธิ์ในการอนุมัติของผู้อนุมัติ</th>*@
                <th rowspan="2">#</th>
            </tr> 
            <tr> 
                @*<th>อนุมัติได้</th>
                <th>ส่งต่อได้</th>
                <th>ตีกลับได้</th>
                <th>ส่งกลับได้</th> *@
            </tr> 
        </thead>
        <tbody>
            @foreach(var approvePath in appPaths)
            {
                <tr> 
                    <td>@approvePath.StepNo</td>
                    <td>
                        @switch (approvePath.ApproverType)
                        {
                            case ApproverType.JobSiteHead: <span>หัวหน้าสำนัก</span>break;
                            case ApproverType.Position:<span>ตำแหน่ง</span>break;
                            case ApproverType.PositionGroup:<span>กลุ่มตำแหน่ง</span>break;
                            case ApproverType.ExecPositionGroup:<span>ตำแหน่งบริหาร</span>break;
                            case ApproverType.FieldApplyTo:<span>ผู้นำไปใช้</span>break;
                            case ApproverType.FieldRelatedTo:<span>ผู้ที่เกี่ยวข้อง</span>break;
                            default:<span>@approvePath.ApproverType.ToString()</span>break;
                        }
                    </td>
                    <td>
                        @switch (approvePath.ApproverType)
                        {
                            case ApproverType.JobSiteHead:
                                <text>
                                    @exec.ExecPosId - @exec.Name 
                                    @Html.Raw(string.Format(aboutAs, string.Join("\r\n", empHeadName)))
                                </text> 
                                break;
                            case ApproverType.Position:
                                if(approvePath.PosId == null)
                                {
                                    @:ยังไม่ตั้งค่าตำแหน่งที่จะอนุมัติ
                                }
                                else if (approvePath.Position != null)
                                { 
@:@approvePath.Position.PosNo - @approvePath.Position.Name
                                    var firstOrDefault = employees.FirstOrDefault(o => o.PosId == approvePath.PosId);
                                    if (firstOrDefault != null)
                                    {
                                        @Html.Raw(string.Format(aboutAs, firstOrDefault.FullName))
                                    }
                                }
                                else
                                {
                                    @:Position = null (PosId = @approvePath.PosId)
                                }
                                break;
                            case ApproverType.ExecPositionGroup:
                                if(approvePath.ExecutivePosition == null)
                                {
                                    @:ยังไม่ตั้งค่าตำแหน่งการบริหารที่จะอนุมัติ
                                }
                                else if (approvePath.ExecutivePosition != null)
                                {
                                    @approvePath.ExecutivePosition.Name
                                    @Html.Raw(string.Format(aboutAs, listExecPos.FirstOrDefault(o => o.Key == approvePath.ExecPosId).Value))
                                }
                                else
                                {
                                    @:ExecPosGroup = null (ExecPosId = @approvePath.ExecPosId)
                                }
                                break; 
                        }
                    </td>
                    @*
                    <td>
                        @Html.Raw(approvePath.IsForNotice?checkTrue: checkFalse)
                    </td> *@
                    <td>
                        <a href="@Url.Action("Detail", new {Id=approvePath.AppPathId, appPrcId})">ดูข้อมูล</a> |
                        <a href="@Url.Action("Update", new {Id=approvePath.AppPathId, appPrcId})">แก้ไข</a> |
                        <a href="@Url.Action("Delete", new {Id=approvePath.AppPathId, appPrcId})">ลบ</a> 
                    </td>
                </tr>
            }
        </tbody>
    </table>
</div>

@{
    /*var appPathsList = (from e in employees.OrderBy(o => o.Position.PosNo)
                    select new SelectListItem
                            {
                                Text = e.Position.PosNo + " - " + e.Position.Name + "  [" + e.FullName + "]",
                                Value = Convert.ToString(e.EmpId),
                                Selected = e.EmpId == ViewBag.EmpIdTest
                            }).ToList();*/

    int empIdTest1 = Convert.ToInt32(ViewBag.EmpIdTest);
    var appPathsList = (from p in context.Positions.ToList().OrderBy(o => o.PosNo)
                        join e in context.Employees.ToList().DefaultIfEmpty() on p.PosId equals e.PosId
                        select new SelectListItem
                            {
                                Text = (p!= null?p.PosNo + " - " : "") + (p!=null ? p.Name:"") + (e !=null ? "  [" + e.FullName + "]":""),
                                Value = Convert.ToString(e.EmpId),
                                Selected = e.EmpId == empIdTest1
                            }).ToList();
                            
     

    appPathsList.Insert(0, new SelectListItem
        {
            Text = "(เลือกจากพนักงานที่มี)", 
            Value = "", 
            Selected = appPathsList.FirstOrDefault(o=>o.Value == Convert.ToString(ViewBag.EmpIdTest)) == null
        });
}

<h4 class="DetailHeader">ทดสอบการส่งต่อ @Html.DropDownList("empIdTest", appPathsList, new {onChange = "javascript:EmpIdTestChanged()"})</h4>

<iframe id="frame111" style="border:solid 1px grey; width:100%; height: 500px;"></iframe>
@*
<div class="detail" >
    @if(testEmp != null) 
    {// Not use
        <b>โหลดผู้อนุมัติ@(appProc.Name)ได้เป็นดังนี้</b><br /><br />
        Position testEmpPos = testEmp.Position;
        <b>ตัวผู้ขอ : @testEmp.FullName [@testEmpPos.PosNo - @testEmpPos.Name]</b>
        @:&nbsp;<span style="color: rgb(255, 200, 0)">&raquo;</span>&nbsp;
        Position poscur = testEmpPos;
        <br />
        <br />

        foreach (var appPath in appPaths)
        {
            <text>
                @Html.Raw(tabCur)<b>ขั้นตอนที่ @appPath.StepNo</b> ผู้อนุมัติแบบ 
                @if (appPath.ApproverType == ApproverType.JobSiteHead)
                {
                    @: หัวหน้าสำนัก
                }
                else if (appPath.ApproverType == ApproverType.Position)
                {
                    @: ตำแหน่ง
                }
                else if (appPath.ApproverType == ApproverType.PositionGroup)
                {
                    @: กลุ่มตำแหน่ง
                }
                else
                {
                    @: ตำแหน่งบริหาร
                }

    
                @switch (appPath.ApproverType)
                {
                    case ApproverType.JobSiteHead:
                        {
                            int i = 1;
                            if (testEmpPos.ExecPosId == 251)
                            {
                                <span style="color: rgb(177, 177, 177)">เป็นหัวหน้าสำนักอยู่แล้ว (ขั้นตอนนี้ไม่ต้องทำ)</span>
                            }
                            else
                            {
                                if (testEmpPos.WorkingUpperPosition == null)
                                {
                                    <span style="color: rgb(177, 177, 177)">ไม่มีผู้บังคับบัญชาที่เหนือกว่า (ขั้นตอนนี้ไม่ต้องทำ)</span>
                                }
                                else
                                {
                                    while (poscur.WorkingUpperPosition != null)
                                    {@:@(i++)).&nbsp;

                                        poscur = poscur.WorkingUpperPosition;

                                        if (poscur != null)
                                        {<text>@poscur.PosNo - @poscur.Name
                                             [@employees.FirstOrDefault(o => o.PosId == poscur.PosId).FullName]</text>
                                        }

                                        if (poscur.ExecPosId == 251)
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        break;
                    case ApproverType.Position:
                        {
                            var pos = context.Positions.FirstOrDefault(o => o.PosId == appPath.PosId);

                            if (pos == null)
                            {
                                @:ตำแหน่งผิด
                            }
                            else
                            {
                                if (pos.PosId == testEmpPos.PosId)
                                {
                                    <span style="color: rgb(177, 177, 177)">ตำแหน่งของผู้ขอเอง (ขั้นตอนนี้ไม่ต้องทำ)</span>
                                }
                                else
                                {<text>@pos.PosNo - @pos.Name
                                     [@employees.FirstOrDefault(o => o.PosId == pos.PosId).FullName]</text>
                                }
                            }
                        }
                        break;
                }
    
                <span style="color: orange">สิทธิ์ [
                    <span style="color: red">@(appPath.IsApproveAble ? "อนุมัติ" : "")</span>
                    <span style="color: red"> @(appPath.IsRejectable ? "ตีกลับ" : "")</span> 
                    <span style="color: green">@(appPath.IsForwardable ? "ส่งต่อ" : "")</span>
                    ]</span>
                &nbsp;<span style="color: rgb(255, 200, 0)">&raquo;</span>&nbsp;
            </text>
            tabCur += "&nbsp&nbsp&nbsp";
            <br />
            <br />
        }

        @Html.Raw(tabCur)<span style="color: rgb(177, 177, 177)">สิ้นสุดขั้นตอนการอนุมัติ</span>
        
    }
</div>*@

<style type="text/css"> 
    table.mystyle
    {
        border-width: 0 0 1px 1px;
        border-spacing: 0;
        border-collapse: collapse;
        border-style: solid;
    }
    .mystyle td, .mystyle th
    {
        margin: 0;
        padding: 4px;
        border-width: 1px 1px 0 0;
        border-style: solid;
    }
    .mystyle th {
        background-color: rgb(240, 240, 240);
    }
</style>
@HttpContext.Current.Request.ApplicationPath
@section scripts{ 
    <script type="text/javascript"> 
        function EmpIdTestChanged() {
            var applyToEmpId = $('#empIdTest').val();
            var appPrcId = '@appPrcId';
            @{
                string host = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);

                string appRootUrl = HttpContext.Current.Request.ApplicationPath;
                var allPaths = appRootUrl.Split('/');
                appRootUrl = "";
                List<string> collection = new List<string>();
                for(int i = 0 ; i < allPaths.Count() -1 ; i++ )
                {
                    collection.Add(allPaths[i]);
                }
                appRootUrl = string.Join("/", collection.ToArray());
                if (!appRootUrl.EndsWith("/")) //a virtual
                {
                    appRootUrl += "/";
                }
            }
            var url = '@(host)@(appRootUrl)'; 
            url += 'Web.Gims/Task/ApprovePath'; // '@Url.Action("Index", new {appPrcId})' + '&EmpIdTest=' + $('#empIdTest').val();
            url += '?appPrcId=' + appPrcId + '&applyToEmpId=' + applyToEmpId;
            $('#frame111').attr('src', url);
        }

    </script>
}